<template>
  <div class="course-container">
    <!-- 查询条件 -->
    <div class="card search-card">
      <el-input v-model="data.searchParams.name" placeholder="请输入课程名称" clearable style="width: 300px" />
      <el-button type="primary" @click="loadCourseData" style="margin-left: 10px">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 课程表格 -->
    <div class="card table-card">
      <el-table :data="data.courseList" border stripe v-loading="data.loading">
        <el-table-column prop="name" label="课程名称" width="180" />
        <el-table-column prop="teacherName" label="授课教师" width="120" />
        <el-table-column prop="time" label="上课时间" width="150" />
        <el-table-column prop="location" label="上课地点" width="150" />

        <!-- 动态操作列 -->
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <template v-if="data.user.role === 'TEACHER'">
                <el-button type="primary" size="small" @click="openCreateSignInDialog(row.id)">发布签到</el-button>
                <el-button type="success" size="small" @click="viewSignInStats(row.id)">统计</el-button>
                <el-button type="warning" size="small" @click="viewSignInRecords(row.id)">记录</el-button>
              </template>
              <el-button
                  v-else
                  type="primary"
                  size="small"
                  @click="openStudentSignInDialog(row.id)">
                签到
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="data.pagination.current"
            v-model:page-size="data.pagination.size"
            :total="data.pagination.total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadCourseData"
            @current-change="loadCourseData"
        />
      </div>
    </div>

    <!-- 教师：发布签到弹窗 -->
    <el-dialog v-model="data.dialog.createSignInVisible" title="发布签到" width="500px">
      <el-form :model="data.signInForm" label-width="120px">
        <el-form-item label="签到时长（分钟）" required>
          <el-input-number
              v-model="data.signInForm.duration"
              :min="1"
              :max="120"
              controls-position="right"
          />
        </el-form-item>
        <el-form-item label="位置验证" prop="locationCheck">
          <el-switch v-model="data.signInForm.locationCheck" />
          <span style="margin-left: 10px; color: #666">
            {{ data.signInForm.locationCheck ? '开启' : '关闭' }}位置验证
          </span>
        </el-form-item>
        <el-form-item
            label="最大签到距离(m)"
            prop="distance"
            v-if="data.signInForm.locationCheck"
            :rules="[{ required: true, message: '请输入最大距离', trigger: 'blur' }]"
        >
          <el-input-number
              v-model="data.signInForm.distance"
              :min="10"
              :max="1000"
              controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="data.dialog.createSignInVisible = false">取消</el-button>
        <el-button type="primary" @click="createSignIn" :loading="data.submitting">确认发布</el-button>
      </template>
    </el-dialog>

    <!-- 教师：签到统计弹窗 -->
    <el-dialog v-model="data.dialog.statsVisible" title="签到统计" width="500px">
      <div v-if="data.signInStats" class="stats-container">
        <el-descriptions border :column="2">
          <el-descriptions-item label="应到人数">{{ data.signInStats.totalCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="实到人数">{{ data.signInStats.signedCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="签到率" :span="2">
            <el-progress
                :percentage="calculateSignInRate()"
                :stroke-width="20"
                status="success"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <el-empty v-else description="暂无统计数据" />
    </el-dialog>

    <!-- 教师：签到记录弹窗 -->
    <el-dialog v-model="data.dialog.recordsVisible" title="签到记录" width="80%">
      <el-table :data="data.signInRecords" border>
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="createTime" label="签到时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'SUCCESS' ? 'success' : 'danger'">
              {{ row.status === 'SUCCESS' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="distance" label="签到距离(m)" width="120" />
      </el-table>
    </el-dialog>

    <!-- 学生：签到弹窗 -->
    <el-dialog v-model="data.dialog.studentSignInVisible" title="课程签到" width="450px">
      <div v-if="data.activeSignIn" class="signin-container">
        <div class="signin-header">
          <h3>{{ data.activeSignIn.courseName }}</h3>
          <p>签到剩余时间: <span class="countdown">{{ formatCountdown }}</span></p>
        </div>

        <div class="signin-body">
          <el-alert
              v-if="data.activeSignIn.locationCheck"
              title="本次签到需要位置验证"
              type="warning"
              show-icon
              style="margin-bottom: 20px"
          />

          <el-button
              type="primary"
              size="large"
              @click="handleStudentSignIn"
              :loading="data.signingIn"
              style="width: 100%"
          >
            {{ data.signingIn ? '正在签到...' : '立即签到' }}
          </el-button>
        </div>
      </div>
      <el-empty v-else description="当前没有进行中的签到" />
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, computed, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';

const data = reactive({
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  searchParams: {
    name: ''
  },
  pagination: {
    current: 1,
    size: 10,
    total: 0
  },
  loading: false,
  submitting: false,
  signingIn: false,
  courseList: [],
  activeSignIn: null,
  signInStats: null,
  signInRecords: [],
  signInForm: {
    courseId: null,
    duration: 10,
    locationCheck: true,
    distance: 100
  },
  dialog: {
    createSignInVisible: false,
    statsVisible: false,
    recordsVisible: false,
    studentSignInVisible: false
  },
  countdown: 0,
  countdownInterval: null
});

// 计算属性
const formatCountdown = computed(() => {
  const minutes = Math.floor(data.countdown / 60);
  const seconds = data.countdown % 60;
  return `${minutes}分${seconds}秒`;
});

// 数据加载
const loadCourseData = async () => {
  try {
    data.loading = true;
    const params = {
      ...data.searchParams,
      pageNum: data.pagination.current,
      pageSize: data.pagination.size,
      withSignIns: true
    };

    if (data.user.role === 'TEACHER') {
      params.teacherId = data.user.id;
    } else if (data.user.role === 'STUDENT') {
      params.classId = data.user.classId;
    }

    const res = await request.get('/course/selectPage', { params });
    data.courseList = res.data?.list || [];
    data.pagination.total = res.data?.total || 0;
  } catch (error) {
    ElMessage.error('加载课程数据失败: ' + (error.response?.data?.msg || error.message));
  } finally {
    data.loading = false;
  }
};

const resetSearch = () => {
  data.searchParams.name = '';
  loadCourseData();
};

// 教师签到相关
const openCreateSignInDialog = (courseId) => {
  data.signInForm = {
    courseId,
    duration: 10,
    locationCheck: true,
    distance: 100
  };
  data.dialog.createSignInVisible = true;
};

const createSignIn = async () => {
  try {
    data.submitting = true;
    const payload = {
      courseId: data.signInForm.courseId,
      duration: data.signInForm.duration,
      locationCheck: data.signInForm.locationCheck,
      distance: data.signInForm.locationCheck ? data.signInForm.distance : 0
    };

    const res = await request.post('/signIn/create', payload);
    if (res.code === '200') {
      ElMessage.success('签到发布成功');
      data.dialog.createSignInVisible = false;
      await loadCourseData();
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '发布签到失败');
  } finally {
    data.submitting = false;
  }
};

const viewSignInStats = async (courseId) => {
  try {
    const res = await request.get('/signIn/stats', { params: { courseId } });
    data.signInStats = res.data || {};
    data.dialog.statsVisible = true;
  } catch (error) {
    ElMessage.error('获取签到统计失败: ' + (error.response?.data?.msg || error.message));
  }
};

const calculateSignInRate = () => {
  if (!data.signInStats || data.signInStats.totalCount === 0) return 0;
  return Math.round((data.signInStats.signedCount / data.signInStats.totalCount) * 100);
};

const viewSignInRecords = async (courseId) => {
  try {
    const res = await request.get('/signIn/records', { params: { courseId } });
    data.signInRecords = res.data || [];
    data.dialog.recordsVisible = true;
  } catch (error) {
    ElMessage.error('获取签到记录失败: ' + (error.response?.data?.msg || error.message));
  }
};

// 学生签到相关
const openStudentSignInDialog = async (courseId) => {
  try {
    const res = await request.get('/signIn/active', {
      params: {
        courseId,
        studentId: data.user.id
      }
    });

    if (res.data) {
      data.activeSignIn = res.data;
      const remaining = Math.floor((new Date(res.data.endTime) - new Date()) / 1000);
      startCountdown(remaining > 0 ? remaining : 60);
      data.dialog.studentSignInVisible = true;
    } else {
      ElMessage.warning('当前没有进行中的签到');
    }
  } catch (error) {
    ElMessage.error('获取签到信息失败: ' + (error.response?.data?.msg || error.message));
  }
};

const startCountdown = (seconds) => {
  clearInterval(data.countdownInterval);
  data.countdown = seconds;

  data.countdownInterval = setInterval(() => {
    data.countdown--;
    if (data.countdown <= 0) {
      clearInterval(data.countdownInterval);
      ElMessage.warning('签到已结束');
      data.dialog.studentSignInVisible = false;
    }
  }, 1000);
};

const handleStudentSignIn = () => {
  if (data.activeSignIn.locationCheck) {
    getLocationAndSignIn();
  } else {
    submitSignIn(null, null);
  }
};

const getLocationAndSignIn = () => {
  if (!navigator.geolocation) {
    ElMessage.error('您的浏览器不支持地理位置功能');
    return;
  }

  data.signingIn = true;

  navigator.geolocation.getCurrentPosition(
      (position) => {
        submitSignIn(position.coords.latitude, position.coords.longitude);
      },
      (error) => {
        data.signingIn = false;
        let message = '获取位置失败';
        switch(error.code) {
          case error.PERMISSION_DENIED:
            message = '用户拒绝了位置请求';
            break;
          case error.POSITION_UNAVAILABLE:
            message = '位置信息不可用';
            break;
          case error.TIMEOUT:
            message = '获取位置超时';
            break;
        }
        ElMessage.error(message);
      },
      { enableHighAccuracy: true, timeout: 10000 }
  );
};

const submitSignIn = async (lat, lng) => {
  try {
    const params = {
      courseId: data.activeSignIn.courseId,
      lat: lat || null,
      lng: lng || null,
      studentId: data.user.id
    };

    const res = await request.post('/signIn/record', params);
    if (res.code === '200') {
      ElMessage.success('签到成功');
      data.dialog.studentSignInVisible = false;
    } else {
      ElMessage.error(res.msg || '签到失败');
    }
  } catch (error) {
    ElMessage.error('签到失败: ' + (error.response?.data?.msg || error.message));
  } finally {
    data.signingIn = false;
  }
};

onMounted(() => {
  loadCourseData();
});

onBeforeUnmount(() => {
  clearInterval(data.countdownInterval);
});
</script>

<style scoped>
.course-container {
  padding: 20px;
}

.card {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  padding: 20px;
}

.search-card {
  display: flex;
  align-items: center;
}

.table-card {
  position: relative;
  min-height: 200px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.stats-container {
  padding: 10px;
}

.signin-container {
  text-align: center;
}

.signin-header {
  margin-bottom: 20px;
}

.signin-header h3 {
  margin-bottom: 10px;
}

.countdown {
  color: #f56c6c;
  font-weight: bold;
}

.signin-body {
  margin-top: 30px;
}

.el-progress {
  margin-top: 10px;
}
</style>